package com.lyw.GeoLocationClient.ui;

import android.app.ProgressDialog;
import android.content.*;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.bmob.v3.listener.SaveListener;
import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.lyw.GeoLocationClient.App;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.utils.StringUtils;
import com.lyw.GeoLocationClient.bean.BmobUser;
import com.lyw.GeoLocationClient.service.LBSClient;
import com.lyw.GeoLocationClient.service.LBSManager;

import static com.lyw.GeoLocationClient.utils.LogUtils.LOGD;

public class AdminRegisterActivity extends BaseActivity implements OnClickListener {

    private Button register;
    private EditText userName, pwd;
    private EditText p_id, name, unit;
    public ProgressDialog loginProDialog;

    private LBSClient mClient;
    private boolean flag;
    private ProgressDialog progressDialog;

    private LBSManager manager;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.admin_login);

        mClient = LBSClient.getInstance();
        if (mClient == null) {
            bindService();
        }
        if (getActionBar() != null) {
            getActionBar().show();
        }

		register = (Button) findViewById(R.id.admin_register);
        //只能使用英文+数字
		userName = (EditText) findViewById(R.id.admin_user_name);
        pwd = (EditText) findViewById(R.id.admin_pwd);
        p_id = (EditText) findViewById(R.id.admin_p_id);
		name = (EditText) findViewById(R.id.admin_name);
        unit = (EditText) findViewById(R.id.admin_unit);

		register.setOnClickListener(this);

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);

        findViewById(R.id.admin_login).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(AdminRegisterActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void showProgress(String msg) {
        progressDialog.setMessage(msg);
        progressDialog.show();
    }


    private void hideProgress() {
        if (progressDialog != null
                && progressDialog.isShowing())
        progressDialog.cancel();
    }

    private void startAdminActivity() {
        LOG("startAdminActivity");

        startActivity(new Intent(this, MapActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    }

    private void startLoginActivity() {
        startActivity(new Intent(this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

    }

    private void bindService() {
        Intent intent = new Intent(this, LBSClient.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private void unBind(){
        if(flag){
            unbindService(conn);
            flag = false;
        }
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            LOG("connected service");
            LBSClient.MyBinder binder = (LBSClient.MyBinder) service;
            mClient = binder.getService();
            manager = mClient.getLbsManager();
            flag = true;
        }
    };

	@Override
	public void onClick(View v) {
        if (!checkInput()) {
            makeToast(getResources().getString(R.string.field_not_null_notice));
            return;
        }

        if (v.getId() == R.id.admin_register) {
            disableButtons();
            showProgress(getResources().getString(R.string.logining));
            registerAdmin();
        }
    }

    private void registerAdmin() {
        if (manager == null) {
            manager = mClient.getLbsManager();
        }
        final String username = getEditViewText(userName);
        final String password = getEditViewText(pwd);

        final BmobUser user = new BmobUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setIsAdmin(true);
        user.setPolId(getEditViewText(p_id));
        user.setName(getEditViewText(name));
        user.setImei(App.ADMIN_IMEI);

        user.setUnit(getEditViewText(unit));
        user.setGroup("admin");

        user.signUp(AdminRegisterActivity.this, new SaveListener() {

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                try {
                    // 调用sdk注册方法
                    EMChatManager.getInstance().createAccountOnServer(username, password);
                    registerSuccess();
                    registerEaseMod(username, password, user.getName());
                } catch (final EaseMobException e) {
                    registerFailed();
                }

            }

            @Override
            public void onFailure(int arg0, String arg1) {
                registerFailed();
            }
        });


    }

    private void registerEaseMod(final String username, final String pwd, final String nick) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 调用sdk注册方法
                    EMChatManager.getInstance().createAccountOnServer(username, pwd);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!AdminRegisterActivity.this.isFinishing())
                                hideProgress();
                            // 保存用户名
                            App.getInstance().setUserName(username);
                            Toast.makeText(getApplicationContext(), R.string.register_ease_ok, 0).show();

                            //更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                            App.currentUserNick = nick;
                            boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(App.currentUserNick.trim());
                            if (!updatenick) {
                                Log.e("LoginActivity", "update current user nick fail");
                            }

                            finish();
                        }
                    });
                } catch (final EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!AdminRegisterActivity.this.isFinishing())
                                hideProgress();
                            int errorCode=e.getErrorCode();
                            if(errorCode== EMError.NONETWORK_ERROR){
                                Toast.makeText(getApplicationContext(), R.string.network_anomalies, Toast.LENGTH_SHORT).show();
                            }else if(errorCode== EMError.USER_ALREADY_EXISTS){
                                Toast.makeText(getApplicationContext(), R.string.User_already_exists, Toast.LENGTH_SHORT).show();
                            }else if(errorCode== EMError.UNAUTHORIZED){
                                Toast.makeText(getApplicationContext(), R.string.registration_failed_without_permission, Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(getApplicationContext(), R.string.Registration_failed + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        }).start();
    }

    private void registerFailed() {
        enableButtons();
        hideProgress();
        makeToast(getResources().getString(R.string.register_failed));
    }

    private void registerSuccess() {
        enableButtons();
        hideProgress();
        makeToast(getResources().getString(R.string.register_success));
        App.getSpUtil().setAdminRegisted(false);
        startLoginActivity();
    }

    private boolean checkInput() {
        boolean isValid = false;
        isValid = !StringUtils.isNullOrEmpty(userName.getText().toString())
                && !StringUtils.isNullOrEmpty(pwd.getText().toString())
                && !StringUtils.isNullOrEmpty(p_id.getText().toString())
                && !StringUtils.isNullOrEmpty(name.getText().toString())
                && !StringUtils.isNullOrEmpty(unit.getText().toString());
        return isValid;
    }

    private void enableButtons() {
        register.setEnabled(true);
    }

    private void disableButtons() {
        register.setEnabled(false);
    }

    private String getEditViewText(EditText v) {
        return v.getText() == null ? "":v.getText().toString();
    }

    public void makeToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unBind();
        hideProgress();
    }

    public void LOG(String msg) {
        LOGD(this.getClass(), msg);
    }

}